package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleService apArticleService;
    /**
     * 生成静态文件上传到minIO中
     * @param article
     * @param content
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle article, String content) {
        if(StringUtils.isNotBlank(content)) {
            // 2. 文章内容通过freemarker生成html文件
            Template template = null;
            StringWriter out = null;
            try {
                template = configuration.getTemplate("article.ftl");
                //    数据模型
                Map<String, Object> data = new HashMap<>();
                data.put("content", JSONArray.parseArray(content));
                out = new StringWriter();
                //    合成
                template.process(data, out);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // 3. 把html上传到minio中
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", article.getId()+".html", in);
            // 4. 修改ap_article表, 保存static_url字段
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId, article.getId()).set(ApArticle::getStaticUrl, path));

            // kafka: 新增文章创建索引, 发送消息
            createArticleESIndex(article, content, path);
        }
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private void createArticleESIndex(ApArticle article, String content, String path) {

        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(article, searchArticleVo);
        searchArticleVo.setContent(content);
        searchArticleVo.setStaticUrl(path);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));
    }
}
